/*
 *  Copyright 2012 Anton Van Zyl. http://code.google.com/p/java-swiss-knife/
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package com.knife.String;

import java.util.List;

import com.knife.LongestCommonSubsequence;

/**
 * Example:<br/>
 * <code><pre> LcsString seq = new LcsString("the quick brown fox", "the Fast brown dog");
		System.out.println("LCS: " + seq.getLcsLength());
		System.out.println("Edit Dist: " + seq.getMinEditDistance());
		System.out.println("Backtrack: " + seq.backtrack());
		System.out.println("HTML Diff: " + seq.getHtmlDiff());</pre></code> <br/>
 * <br/>
 * Please visit <a
 * href="http://code.google.com/p/java-swiss-knife/">Java-Swiss-Knife</a> and
 * comment, rate, contribute or raise a issue/enhancement for my library. <br/>
 * 
 * @author Anton Van Zyl
 * 
 */
public final class LcsString extends LongestCommonSubsequence<Character> {
	private String x;
	private String y;

	public LcsString(String from, String to) {
		this.x = from;
		this.y = to;
	}

	protected int lengthOfY() {
		return y.length();
	}

	protected int lengthOfX() {
		return x.length();
	}

	protected Character valueOfX(int index) {
		return x.charAt(index);
	}

	protected Character valueOfY(int index) {
		return y.charAt(index);
	}

	public String getHtmlDiff() {
		DiffType type = null;
		List<DiffEntry<Character>> diffs = diff();
		StringBuffer buf = new StringBuffer();

		for (DiffEntry<Character> entry : diffs) {
			if (type != entry.getType()) {
				if (type != null) {
					buf.append("</span>");
				}
				buf.append("<span class=\"" + entry.getType().getName() + "\">");
				type = entry.getType();
			}
			buf.append(escapeHtml(entry.getValue()));
		}
		buf.append("</span>");
		return buf.toString();
	}

	private String escapeHtml(Character ch) {
		switch (ch) {
		case '<':
			return "&lt;";
		case '>':
			return "&gt;";
		case '"':
			return "\\&quot;";
		default:
			return ch.toString();
		}
	}

}